﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Mail;
using SendMailApplication.Helper;
using System.Collections.Generic;
using SendMailApplication.DataType;
using System.Net.Mime;
using FirebirdSql.Data.FirebirdClient;

namespace SendMailApplication
{
    class Program
    {
        static void Main(string[] args)
        {

            List<object> allMail = Common.callProcedureQuery("TNH_GETALLMAIL", null, new DTMailInfo());
            Dictionary<string, string> mapHost = new Dictionary<string, string>();
            mapHost.Add("google", "smtp.gmail.com");
            mapHost.Add("outlook", "smtp.live.com");
            mapHost.Add("yahoo", "smtp.mail.yahoo.com");

            if (allMail != null && allMail.Count > 0)
            {
                for (int i = 0; i < allMail.Count; i++)
                {
                    MailObj obj = (MailObj)allMail[i];
                    var smtp = new SmtpClient
                    {
                        Host = mapHost[obj.service],
                        Port = 587,
                        EnableSsl = true,
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,
                        Credentials = new NetworkCredential(obj.fromAddress, obj.passWd)
                    };

                    string[] lines = System.IO.File.ReadAllLines(obj.contentPath);
                    String content = "";
                    foreach (string line in lines)
                    {
                        content += line;
                    }
                    using (var message = new MailMessage(obj.fromAddress, obj.toAddress)
                    {
                        Subject = obj.subject,
                        Body = content,
                        IsBodyHtml = true

                    })
                    {
                        string[] splitPath = obj.filePath.Split(new char[] { '\\' });
                        Attachment attachment = AttachmentHelper.CreateAttachment(obj.filePath, splitPath[splitPath.Length - 1], TransferEncoding.Base64);
                        message.Attachments.Add(attachment);
                        smtp.Send(message);

                        FbCommand cm = new FbCommand();
                        FbParameterCollection pc = cm.Parameters;
                        pc.Add("@MCLID", FbDbType.Integer).Value = obj.mclid;

                        Common.callProcedureQuery("TNH_UPDATE_MAILINFO", pc);
                    };
                }
            }
        }
    }
}
